package cn.smbms.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.smbms.pojo.PageUtil;
import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.RoleServiceI;
import cn.smbms.service.UserServiceI;

import com.alibaba.fastjson.JSONArray;

@Controller
public class UserController {
	// Logger logger = Logger.getLogger(getClass());
	// Logger logger;
	private static final org.slf4j.Logger selflogger = LoggerFactory
			.getLogger(UserController.class);
	private static final org.apache.log4j.Logger log4jlogger = org.apache.log4j.Logger
			.getLogger(UserController.class);

	@Autowired
	private UserServiceI userService;
	@Autowired
	private RoleServiceI roleService;
	public static final String PAGEPATH = "/WEB-INF/jsp/";

	// @RequestMapping(value = "/add1", method = RequestMethod.GET)
	// public String welcome3() {
	// System.out.println("hello,SpringMVC!>>>>");
	// return "userAdd";
	// }
	//
	// @RequestMapping(value = "/add2", method = RequestMethod.POST)
	// public String add2(@ModelAttribute("user") User user) {
	// System.out.println("你输入的是" + user);
	// userService.addUser(user);
	// return "redirect:add1.do";
	// }
	//
	// @RequestMapping(value = "/login2", method = RequestMethod.POST)
	// public String test(String userCode, String password, Map<String, Object>
	// map) {
	// if (userService.login(userCode, password) != null) {
	// System.out.println("hello,SpringMVC!>>>>" + userCode + ":>>>" +
	// password);
	// return "welcome";
	// }
	// return "login";
	// }
	//
	@RequestMapping(value = "/yanZhengUserCodeExists")
	@ResponseBody
	public Object yanZhengUserCodeExists(@RequestParam String userCode) {
		System.out.println("userCode>>>" + userCode);
		HashMap<String, String> resultMap = new HashMap<String, String>();
		if (null == userCode || "".equals(userCode)) {
			resultMap.put("msg", "exists");
		} else {
			boolean i = userService.yanZhengUserCodeExists(userCode);
			if (i) {
				resultMap.put("msg", "exist");
			} else {
				resultMap.put("msg", "notExist");
			}
		}
		return JSONArray.toJSONString(resultMap);
	}

	@RequestMapping(value = "user-login")
	public void loginMVC2(
			@RequestParam(value = "opr", required = false) String opr,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		selflogger
				.debug("debug\ndebug\ndebug\ndebug\ndebug\ndebug\ndebug\ndebug\ndebug\ndebug\ndebug\nv");
		selflogger
				.info("info\ninfo\ninfo\ninfo\ninfo\ninfo\ninfo\ninfo\ninfo\ninfo\ninfo\n");
		selflogger
				.warn("warn\nwarn\nwarn\nwarn\nwarn\nwarn\nwarn\nwarn\nwarn\nwarn\nwarn\nwarn\n");
		selflogger
				.error("error\nerror\nerror\nerror\nerror\nerror\nerror\nerror\nerror\nerror\n");
		log4jlogger
				.debug("debugdebug\ndebugdebug\ndebugdebug\ndebugdebug\ndebugdebug\ndebugdebug\ndebugdebug\ndebugdebug\n");
		log4jlogger
				.info("infoinfo\ninfoinfo\ninfoinfo\ninfoinfo\ninfoinfo\ninfoinfo\ninfoinfo\ninfoinfo\n");
		log4jlogger
				.warn("warnwarn\nwarnwarn\nwarnwarn\nwarnwarn\nwarnwarn\nwarnwarn\nwarnwarn\nwarnwarn\n");
		log4jlogger
				.error("errorerror\nerrorerror\nerrorerror\nerrorerror\nerrorerror\nerrorerror\nerrorerror\n");
		if ("show".equals(opr)) {
			String userCode = request.getParameter("userCode");
			request.setAttribute("userCode", userCode);
			request.getRequestDispatcher(PAGEPATH + "login.jsp").forward(
					request, response);
			return;
		} else if ("yanZhengUserCodeExists".equals(opr)) {
			String userCode = request.getParameter("userCode");
			boolean i = userService.yanZhengUserCodeExists(userCode);
			response.getWriter().print(i);
			return;
		} else if ("login".equals(opr)) {
			String userCode = request.getParameter("userCode");
			String userPassword = request.getParameter("userPassword");

			User user = userService.login(userCode, userPassword);

			if (user != null) {
				request.getSession().setAttribute("USER", user);
				request.getRequestDispatcher(PAGEPATH + "welcome.jsp").forward(
						request, response);
				return;
			} else {
				throw new RuntimeException("用户名或密码不正确！");
				// response.getWriter().print("<script>alert('用户名或密码不正确！');location.href='user-login.do?opr=show&userCode="
				// + userCode + "'</script>");
				// return;
			}
		} else if ("loginOut".equals(opr)) {
			request.getSession().invalidate();
			response.sendRedirect("user-login.do?opr=show");
			return;
		}
	}

	@ExceptionHandler(value = { RuntimeException.class })
	public String handlerException(RuntimeException e,
			HttpServletRequest request) {
		request.setAttribute("exception", e);
		return "login";
	}

	@RequestMapping(value = "废弃>>>user-login")
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opr = request.getParameter("opr");
		if ("show".equals(opr)) {
			String userCode = request.getParameter("userCode");
			request.setAttribute("userCode", userCode);
			request.getRequestDispatcher(PAGEPATH + "login.jsp").forward(
					request, response);
			return;
		} else if ("yanZhengUserCodeExists".equals(opr)) {
			String userCode = request.getParameter("userCode");
			boolean i = userService.yanZhengUserCodeExists(userCode);
			response.getWriter().print(i);
			return;
		} else if ("login".equals(opr)) {
			String userCode = request.getParameter("userCode");
			String userPassword = request.getParameter("userPassword");

			User user = userService.login(userCode, userPassword);

			if (user != null) {
				request.getSession().setAttribute("USER", user);
				request.getRequestDispatcher(PAGEPATH + "welcome.jsp").forward(
						request, response);
				return;
			} else {
				response.getWriter().print(
						"<script>alert('用户名或密码不正确！');location.href='user-login.do?opr=show&userCode="
								+ userCode + "'</script>");

				return;
			}
		} else if ("loginOut".equals(opr)) {
			request.getSession().invalidate();
			response.sendRedirect("user-login.do?opr=show");
			return;
		}
	}

	@RequestMapping(value = "user-updatePwd")
	public void updatePwd(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String opr = request.getParameter("opr");
		if ("show".equals(opr)) {
			request.getRequestDispatcher(PAGEPATH + "password.jsp").forward(
					request, response);
			return;
		} else if ("yanZhengOldPassword".equals(opr)) {
			User user = (User) request.getSession().getAttribute("USER");
			Integer id = user.getId();
			String password = request.getParameter("oldPassword");
			boolean i = userService.yanZhengOldPassword(id, password);
			response.getWriter().print(i);
			return;
		} else if ("updatePwd".equals(opr)) {
			User user = (User) request.getSession().getAttribute("USER");
			Integer id = user.getId();
			String password = request.getParameter("password");

			int i = userService.updatePwd(id, password);

			if (i > 0) {
				response.getWriter()
						.print("<script>alert('修改密码成功！');location.href='user-updatePwd.do?opr=showWelcome'</script>");
				return;
			} else {
				response.getWriter()
						.print("<script>alert('修改密码失败！');location.href='user-updatePwd.do?opr=show'</script>");
				return;
			}
		} else if ("showWelcome".equals(opr)) {
			request.getRequestDispatcher(PAGEPATH + "welcome.jsp").forward(
					request, response);
			return;
		}

	}

	@RequestMapping(value = "user-getUserList")
	public ModelAndView getUserList(
			@RequestParam(value = "userName", required = false) String userName,
			@RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage) {
		List<User> userList = userService.getUserListByUserName(userName,
				currentPage);
		int count = userService.count(userName);
		PageUtil page = new PageUtil();
		page.setTotalCount(count);
		page.setCurrentPage(currentPage);
		page.setRows(userList);
		ModelAndView mv = new ModelAndView();
		mv.addObject("page", page);
		mv.addObject("userName", userName);
		mv.setViewName("userList");
		return mv;
	}

	@RequestMapping(value = "废弃>>>user-getUserList")
	public void getUserList(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userName = request.getParameter("userName");
		Integer currentPage = 1;
		try {
			currentPage = Integer.parseInt(request.getParameter("currentPage"));
		} catch (NumberFormatException e) {
		}
		List<User> userList = userService.getUserListByUserName(userName,
				currentPage);
		int count = userService.count(userName);

		PageUtil page = new PageUtil();
		page.setTotalCount(count);
		page.setCurrentPage(currentPage);
		page.setRows(userList);
		request.setAttribute("page", page);
		request.setAttribute("userName", userName);
		request.getRequestDispatcher(PAGEPATH + "userList.jsp").forward(
				request, response);

	}

	@RequestMapping(value = "user-getUserById")
	public void getUserById(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String opr = request.getParameter("opr");
		Integer userId = null;
		try {
			userId = Integer.parseInt(request.getParameter("userId"));
		} catch (NumberFormatException e) {
		}
		User user = userService.getUserById(userId);
		request.setAttribute("user", user);
		if ("Update".equals(opr)) {
			List<Role> roleList = roleService.getAllIdAndRoleName();
			request.setAttribute("roleList", roleList);
		}
		request.getRequestDispatcher(PAGEPATH + "user" + opr + ".jsp").forward(
				request, response);

	}

	@RequestMapping(value = "JSONuser-getUserById")
	@ResponseBody
	public User JSONgetUserById(@RequestParam Integer userId)
			throws ServletException, IOException {
		return userService.getUserById(userId);

	}

	//
	// @RequestMapping(value = "JSONuser-getUserById")
	// @ResponseBody
	// public Object JSONgetUserById(@RequestParam Integer userId) throws
	// ServletException, IOException {
	// String cjson = "";
	// if (null == userId || "".equals(userId)) {
	// return "nodata";
	// } else {
	// User user = userService.getUserById(userId);
	// cjson = JSON.toJSONString(user);
	// System.out.println(cjson);
	// }
	// return cjson;
	// }
	// @RequestMapping(value = "JSONuser-getUserById", produces = {
	// "application/json;charset=utf-8" })
	// @ResponseBody
	// public Object JSONgetUserById(@RequestParam Integer userId) throws
	// ServletException, IOException {
	// String cjson = "";
	// if (null == userId || "".equals(userId)) {
	// return "nodata";
	// } else {
	// User user = userService.getUserById(userId);
	// cjson = JSON.toJSONString(user);
	// System.out.println(cjson);
	// }
	// return cjson;
	// }

	@RequestMapping(value = "废弃>>>user-addUser")
	public void addUser(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String opr = request.getParameter("opr");
		if (opr.equals("show")) {
			List<Role> roleList = roleService.getAllIdAndRoleName();
			request.setAttribute("roleList", roleList);
			request.getRequestDispatcher(PAGEPATH + "userAdd.jsp").forward(
					request, response);
			return;
		} else if (opr.equals("add")) {
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
			String userCode = request.getParameter("userCode");
			String userName = request.getParameter("userName");
			String userPassword = request.getParameter("userPassword");
			Integer gender = null;
			try {
				gender = Integer.parseInt(request.getParameter("gender"));
			} catch (NumberFormatException e) {
			}
			String birthday = request.getParameter("birthday");
			String phone = request.getParameter("phone");
			String address = request.getParameter("address");
			Integer userRole = null;
			try {
				userRole = Integer.parseInt(request.getParameter("userRole"));
			} catch (NumberFormatException e) {
			}
			Date pbirthday = null;
			try {
				pbirthday = sf.parse(birthday);
			} catch (ParseException e) {
			}
			User u = new User(userCode, userName, userPassword, gender,
					pbirthday, phone, address, userRole);
			int i = userService.addUser(u);
			response.getWriter()
					.print("<script>alert('用户增加"
							+ (i == 1 ? "成功" : "失败")
							+ "！');location.href='user-getUserList.do';</script>");

		}

	}

	@RequestMapping(value = "user-addUser", method = RequestMethod.GET)
	public String add1(Model model) throws Exception {
		List<Role> roleList = roleService.getAllIdAndRoleName();
		model.addAttribute("roleList", roleList);
		return "userAdd";
	}

	@RequestMapping(value = "user-addUser", method = RequestMethod.POST)
	public String add2(
			@ModelAttribute("user") User u,
			HttpSession session,
			@RequestParam(value = "picture", required = false) MultipartFile[] fs)
			throws Exception {
		for (int i = 0; i < fs.length; i++) {
			MultipartFile f = fs[i];
			if (!f.isEmpty()) {
				System.out.println(">>>元素名：" + f.getName() + ",原文件名："
						+ f.getOriginalFilename() + ",文件大小：" + f.getSize());
				String oldName = f.getOriginalFilename();
				String uploadFilePath = session.getServletContext()
						.getRealPath("img");
				String suffix = FilenameUtils.getExtension(oldName);

				// String suffix = oldName.substring(oldName.indexOf('.'));
				String newName = UUID.randomUUID() + "." + suffix;
				f.transferTo(new File(uploadFilePath, newName));
				System.out.println("文件的相对路径：img/" + newName);
				if (i == 0) {
					u.setPicPath("img/" + newName);
				} else if (i == 1) {
					u.setWorkPicPath("img/" + newName);
				}
			}
		}
		int i = userService.addUser(u);
		// response.getWriter().print("<script>alert('用户增加" + (i == 1 ? "成功"
		// : "失败")
		// + "！');location.href='user-getUserList.do';</script>");
		return "redirect:user-getUserList.do";

	}

	@RequestMapping(value = "user-updateUser")
	public void updateUser(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		Integer userId = null;
		try {
			userId = Integer.parseInt(request.getParameter("userId"));
		} catch (NumberFormatException e) {
		}
		String userName = request.getParameter("userName");

		Integer gender = null;
		try {
			gender = Integer.parseInt(request.getParameter("gender"));
		} catch (NumberFormatException e) {
		}
		String birthday = request.getParameter("birthday");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		Integer userRole = null;
		try {
			userRole = Integer.parseInt(request.getParameter("userRole"));
		} catch (NumberFormatException e) {
		}
		Date pbirthday = null;
		try {
			pbirthday = sf.parse(birthday);
		} catch (ParseException e) {
		}
		User u = new User(userId, userName, gender, pbirthday, phone, address,
				userRole);
		int i = userService.updateUser(u);
		response.getWriter().print(
				"<script>alert('用户修改" + (i == 1 ? "成功" : "失败")
						+ "！');location.href='user-getUserList.do';</script>");

	}

	@RequestMapping(value = "废弃>>>user-deleteUser")
	public void deleteUser(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Integer userId = null;
		try {
			userId = Integer.parseInt(request.getParameter("userId"));
		} catch (NumberFormatException e) {
		}
		int i = userService.deleteUser(userId);

		response.getWriter().print(
				"<script>alert('用户删除" + (i == 1 ? "成功" : "失败")
						+ "！');location.href='user-getUserList.do';</script>");

	}

	@RequestMapping(value = "user-deleteUser/{userId}")
	public void deleteUser(@PathVariable Integer userId,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int i = userService.deleteUser(userId);

		response.getWriter()
				.print("<script>alert('用户删除"
						+ (i == 1 ? "成功" : "失败")
						+ "！');location.href='../user-getUserList.do';</script>");

	}

	@InitBinder
	// 提前注册日期的转换器
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, true));
	}

}
